#include "card.h"
#include <QPainter>
#include <QMouseEvent>
#include <QDrag>
#include <QMimeData>
#include <QApplication>
#include <QDataStream>

Card::Card(int value, QWidget* parent)
    : QWidget(parent), m_value(value), m_isFaceUp(false)
{
    setFixedSize(80, 100);
    setAcceptDrops(false);
}

void Card::setFaceUp(bool faceUp) {
    if (m_isFaceUp != faceUp) {
        m_isFaceUp = faceUp;
        update();
    }
}

void Card::paintEvent(QPaintEvent* event) {
    Q_UNUSED(event);
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);

    if (!m_isFaceUp) {
        painter.fillRect(rect(), Qt::darkBlue);
        painter.setPen(Qt::white);
        painter.drawText(rect(), Qt::AlignCenter, "背面");
        return;
    }

    painter.fillRect(rect(), Qt::white);
    painter.setPen(Qt::black);
    painter.drawRect(rect());
    painter.drawText(rect(), Qt::AlignCenter, QString::number(m_value));
}

void Card::mousePressEvent(QMouseEvent* event) {
    if (event->button() == Qt::LeftButton) {
        m_dragStartPos = event->pos();
    }
}

void Card::mouseMoveEvent(QMouseEvent* event) {
    if (!(event->buttons() & Qt::LeftButton))
        return;
    if ((event->pos() - m_dragStartPos).manhattanLength() < QApplication::startDragDistance())
        return;

    QDrag* drag = new QDrag(this);
    QMimeData* mimeData = new QMimeData;

    QByteArray data;
    QDataStream stream(&data, QIODevice::WriteOnly);
    stream << reinterpret_cast<quintptr>(this);
    mimeData->setData("text/card-group", data);
    drag->setMimeData(mimeData);
    drag->exec(Qt::MoveAction);
}
